package org.dromara.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.websocket.EncodeException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.mall.domain.*;
import org.dromara.mall.domain.bo.GoodsBo;
import org.dromara.mall.domain.vo.GoodsVo;
import org.dromara.mall.mapper.*;
import org.dromara.mall.service.IMallGoodsService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 商品列表Service业务层处理
 *
 * @author Lion Li
 * @date 2024-05-21
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class MallGoodsServiceImpl implements IMallGoodsService {

    private final MallGoodsMapper baseMapper;
    private final MallGoodsSkusMapper skusMapper;
    private final MallGoodsDetailsMapper detailsMapper;
    private final MallGoodsSpecMapper specMapper;
    private final MallGoodsSpecValMapper specValMapper;


    /**
     * 查询商品详情
     */
    @Override
    public GoodsVo queryById(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("商品ID不能为空");
        }

        // 查询主表goods
        MallGoods goods = baseMapper.selectById(id);
        if (goods == null) {
            throw new IllegalArgumentException("未找到对应ID的商品");
        }

        GoodsVo goodsVo = new GoodsVo();
        BeanUtils.copyProperties(goods, goodsVo);

        // 查询sku表
        List<MallGoodsSkus> skuList = querySkusById(id);
        goodsVo.setSkus(skuList);

        // 查询规格spec表
        List<MallGoodsSpec> specList = querySpecsById(id);
        goodsVo.setSpecs(specList);

        // 查询商品详情
        MallGoodsDetails details = queryDetailsById(id);
        goodsVo.setDetails(details);

        return goodsVo;
    }

    // 查询sku表-方法
    private List<MallGoodsSkus> querySkusById(Long goodsId) {
        LambdaQueryWrapper<MallGoodsSkus> skuWrapper = new LambdaQueryWrapper<>();
        skuWrapper.eq(MallGoodsSkus::getGoodsId, goodsId);
        List<MallGoodsSkus> skuList = skusMapper.selectList(skuWrapper);

        if (skuList != null) {
            for (MallGoodsSkus sku : skuList) {
                // 处理SKU的spec_id
                processSkuSpecIds(sku);
            }
        }
        return skuList;
    }

    // 查询规格spec表-方法
    private void processSkuSpecIds(MallGoodsSkus sku) {
        String[] specIds = sku.getSpecId().split(",");
        for (String specId : specIds) {
            Long specValueId = Long.valueOf(specId.trim());
            // TODO 用于前端checkBox回显
            List<Long> specIdBySku = specValMapper.findSpecIdBySku(specValueId);
            // 可以在这里处理specIdBySku
        }
    }

    private List<MallGoodsSpec> querySpecsById(Long goodsId) {
        LambdaQueryWrapper<MallGoodsSpec> specWrapper = new LambdaQueryWrapper<>();
        specWrapper.eq(MallGoodsSpec::getGoodsId, goodsId);
        List<MallGoodsSpec> specList = specMapper.selectList(specWrapper);

        if (specList != null) {
            for (MallGoodsSpec spec : specList) {
                // 查询specVal值
                List<MallGoodsSpecVal> specValList = querySpecValsBySpecId(spec.getId());
                spec.setSpecValues(specValList);
            }
        }

        return specList;
    }

    private List<MallGoodsSpecVal> querySpecValsBySpecId(Long specId) {
        LambdaQueryWrapper<MallGoodsSpecVal> valWrapper = new LambdaQueryWrapper<>();
        valWrapper.eq(MallGoodsSpecVal::getSpecId, specId);
        return specValMapper.selectList(valWrapper);
    }

    private MallGoodsDetails queryDetailsById(Long goodsId) {
        LambdaQueryWrapper<MallGoodsDetails> detailWrapper = new LambdaQueryWrapper<>();
        detailWrapper.eq(MallGoodsDetails::getGoodsId, goodsId);
        return detailsMapper.selectOne(detailWrapper);
    }

    /**
     * 查询商品列表列表
     */
    @Override
    public TableDataInfo<GoodsVo> queryPageList(GoodsBo bo, PageQuery pageQuery) {
        Page<GoodsVo> result = baseMapper.queryPageList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * TODO 导出商品列表列表
     */
    @Override
    public List<GoodsVo> queryList(GoodsBo bo) {
        LambdaQueryWrapper<MallGoods> lqw = buildQueryWrapper(bo);
        return null; //TODO
//        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<MallGoods> buildQueryWrapper(GoodsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MallGoods> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getBrandId() != null, MallGoods::getBrandId, bo.getBrandId());
        lqw.eq(bo.getCate3Id() != null, MallGoods::getCate3Id, bo.getCate3Id());
        lqw.like(StringUtils.isNotBlank(bo.getName()), MallGoods::getName, bo.getName());
        lqw.like(StringUtils.isNotBlank(bo.getGoodsNo()), MallGoods::getGoodsNo, bo.getGoodsNo());
        lqw.like(bo.getSale() != null, MallGoods::getSale, bo.getSale());
        lqw.eq(bo.getStatus() != null, MallGoods::getStatus, bo.getStatus());
        lqw.eq(bo.getVerify() != null, MallGoods::getVerify, bo.getVerify());
        lqw.eq(StringUtils.isNotBlank(bo.getContentMobile()), MallGoods::getContentMobile, bo.getContentMobile());
        lqw.eq(bo.getIsRecommend() != null, MallGoods::getIsRecommend, bo.getIsRecommend());
        lqw.eq(bo.getIsMaster() != null, MallGoods::getIsMaster, bo.getIsMaster());
        return lqw;
    }

    /**
     * 新增商品列表
     */
    @Override
    public MallGoods insertByBo(GoodsBo bo) {
        validEntityBeforeSave(bo);
        if (bo.getDetails().getContent() == null) {
            throw new RuntimeException("没有商品详情！");
        }
        MallGoods goods = new MallGoods();
        //TODO 属性拷贝
        BeanUtils.copyProperties(bo, goods);
        boolean flag = baseMapper.insert(goods) > 0;

        if (flag) {
            goods.setId(goods.getId());
            //获取sku列表
            List<MallGoodsSkus> goodsSkus = bo.getSkus();
            if (goodsSkus != null && !goodsSkus.isEmpty()) {
                goodsSkus.forEach(sku -> {
                    //设置商品ID
                    sku.setGoodsId(goods.getId());
                    //保存sku信息到skus表
                    skusMapper.insert(sku);
                });
            }

            //保存详情内容主体到details表
            MallGoodsDetails goodsDetails = new MallGoodsDetails();
            //设置所属商品ID
            goodsDetails.setGoodsId(goods.getId());
            goodsDetails.setContent(bo.getDetails().getContent());
            detailsMapper.insert(goodsDetails);
        }
        return goods;
    }

    /**
     * 修改商品
     */
    @Override
    public MallGoods updateByBo(GoodsBo bo) {
        List<MallGoodsSkus> goodsSkus = bo.getSkus();
        goodsSkus.forEach(sku -> {
            //设置要更新的表
            sku.setGoodsId(bo.getId());
            //如果有新增则执行新增的方法
            if (sku.getId() == null) {
                //设置商品ID
                sku.setGoodsId(bo.getId());
                //保存sku信息到skus表
                skusMapper.insert(sku);
            } else {
                //执行更新方法
                skusMapper.updateById(sku);
            }
        });
        //修改子表details
        MallGoodsDetails details = bo.getDetails();
        //如果增加时未添加详情，则无关联id无法执行编辑，就执行新增
        if (details.getGoodsId() == null) {
            details.setGoodsId(bo.getId());
            details.setContent(bo.getDetails().getContent());
            detailsMapper.insert(details);
        } else {
            details.setGoodsId(bo.getId());
            detailsMapper.updateById(details);
        }
        //修改主表
        MallGoods goods = new MallGoods();
        BeanUtils.copyProperties(bo, goods);
        baseMapper.updateById(goods);
        return goods;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(GoodsBo entity) {
        //TODO 做一些数据校验,如唯一约束，如果没有detail数据，抛异常
        log.info("前端数据，{}", entity);

    }

    /**
     * 批量删除商品列表
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /*商品审核*/
    @Override
    public Boolean updateVerify(Long id, Integer goodsVerify, Boolean b) {
        MallGoods bo = new MallGoods();
        bo.setId(id);
        bo.setVerify(goodsVerify);
        baseMapper.updateById(bo);
        return true;
    }

    /*商品上下架*/
    @Override
    public Boolean updateStatus(Long id, Integer goodsStatus, Boolean b) {
        MallGoods bo = new MallGoods();
        bo.setId(id);
        bo.setStatus(goodsStatus);
        baseMapper.updateById(bo);
        return true;
    }

    /*推荐商家首页*/
    @Override
    public Boolean updateRecommend(Long id, Integer isRecommend, Boolean b) {
        MallGoods bo = new MallGoods();
        bo.setId(id);
        bo.setIsRecommend(isRecommend);
        baseMapper.updateById(bo);
        return true;
    }

    /*推荐主站首页*/
    @Override
    public Boolean updateMaster(Long id, Integer isMaster, Boolean b) {
        MallGoods bo = new MallGoods();
        bo.setId(id);
        bo.setIsMaster(isMaster);
        baseMapper.updateById(bo);
        return true;
    }

    /*删除商品sku列表*/
    @Override
    public Boolean deleteSkuByGoodsId(Collection<Long> ids, Boolean isValid) {
        LambdaQueryWrapper<MallGoodsSkus> skus = new LambdaQueryWrapper<MallGoodsSkus>().in(MallGoodsSkus::getGoodsId, ids);
        if (skus == null) {
            throw new RuntimeException("没有可执行的删除");
        }
        return skusMapper.delete(skus) > 0;
    }
}
